// pages/appointment/appointment.js
//获取应用实例
const app = getApp();
const date = new Date();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    days: [],
    openId: '',
    selectDay: '',
    dateStr: '', //格式化的时间yyyy-MM-dd
    appointments: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isShow: false
  },
  getDate: function() {
    const year = date.getFullYear();
    let month = (date.getMonth() + 1).toString();
    if (month.length == 1) {
      month = '0' + '' + month;
    }
    let day = date.getDate().toString();
    if (day.length == 1) {
      day = '0' + '' + day;
    }
    return year + '-' + month + '-' + day;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          that.setData({
            isShow: true
          });
        }
      }
    });
    app.userCheckCallback = res => {
      this.setData({
        openId: res
      });
      this.check();
    };

    //初始化日期，默认显示后7天
    const days = [];
    const nowDay = new Date();
    //设置当前日期
    this.setData({
      selectDay: nowDay.getMonth() + 1 + '.' + nowDay.getDate()
    });
    const arr = ['日', '一', '二', '三', '四', '五', '六'];
    for (let i = 0; i < 7; i++) {
      const day = nowDay.getMonth() + 1 + '.' + nowDay.getDate();
      const dayObject = {
        dayCh: "周" + "日一二三四五六".charAt(nowDay.getDay()),
        day: day
      };
      nowDay.setDate(nowDay.getDate() + 1);
      days.push(dayObject);
    }
    this.setData({
      days: days
    });
  },
  changeDate: function(e) {
    const index = e.currentTarget.dataset.index;
    const selectDay = this.data.days[index].day;
    this.setData({
      selectDay: selectDay,
      appointments: []
    });
    const arr = selectDay.split('.');
    const year = date.getFullYear();
    const month = arr[0].length == 1 ? '0' + arr[0] : arr[0];
    const day = arr[1].length == 1 ? '0' + arr[1] : arr[1];
    const dateStr = year + '-' + month + '-' + day;
    this.setData({
      dateStr: dateStr
    });
    this.refleshAppointments(dateStr);
  },
  refleshAppointments: function(date) {
    const that = this;
    const url = app.globalData.url;
    const openId = that.data.openId || app.globalData.openId;
    wx.showNavigationBarLoading();
    wx.request({
      url: url + '/appointment/getCoachAppointment',
      data: {
        openId: openId,
        appointmentDate: date
      },
      method: 'POST',
      success: function(response) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
        if (response.data.success) {
          const appointments = response.data.content;
          appointments.forEach(function(item) {
            if (item.traineeName.length > 5) {
              item.traineeName = item.traineeName.substring(0, 3) + '...';
            }
          });
          that.setData({
            appointments: appointments
          });
        }
      }
    })
  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      app.globalData.userInfo = e.detail.userInfo;
      this.setData({
        isShow: false
      });
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '提示',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {}
      });
    }
  },
  check: function() {
    const that = this;
    const url = app.globalData.url;
    const openId = app.globalData.openId || that.data.openId;
    const dateStr = that.data.dateStr;
    if (openId.length > 0) {
      wx.request({
        url: url + '/coach/check/' + openId,
        method: "GET",
        success: function(res) {
          if (res.data.success == false) {
            wx.showToast({
              title: '请先注册',
              icon:'none'
            })
          } else {
            that.refleshAppointments(dateStr);
          }
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const date = this.getDate();
    const selectDay = this.data.days[0].day;
    this.setData({
      dateStr: date,
      selectDay
    });
    this.check();
  },
  onPullDownRefresh: function () {
    const dateStr = this.data.dateStr;
    this.refleshAppointments(dateStr);
  }
})